package com.chexiehui.jc.ui.activity;

import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.AppApplication;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseActivity;
import com.chexiehui.jc.entity.BaiDuLocationInfo;
import com.chexiehui.jc.entity.ChooseCityEvent;
import com.chexiehui.jc.entity.CityInfo;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.widget.indexbar.IndexBar;
import com.chexiehui.jc.widget.indexbar.suspension.SuspensionDecoration;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class ChooseCityActivity extends BaseActivity {
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.ib_right_index_bar)
    IndexBar ibRightIndexBar;
    @BindView(R.id.tv_side_bar_hint)
    TextView tvSideBarHint;
    private CommonAdapter<CityInfo> cityAdapter;
    private List<CityInfo> cityListData;
    private SuspensionDecoration suspensionDecoration;
    private String nowCity = "";
    private double lat;
    private double lng;
    private int eventTag = -1;

    @Override
    protected void beforeSetView() {
        Bundle bundle = getIntent().getExtras();
        if(bundle != null){
            eventTag = bundle.getInt("eventTag", -1);
        }
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("选择城市");
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_choose_city;
    }

    @Override
    protected void initView(Bundle var1) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recycler.setLayoutManager(layoutManager);
        cityListData = new ArrayList<>();
        cityAdapter = new CommonAdapter<CityInfo>(mContext, R.layout.item_city, cityListData) {
            @Override
            protected void convert(ViewHolder holder, CityInfo cityInfo, int position) {
                holder.setText(R.id.tv_item_name, cityInfo.getName());
            }
        };
        cityAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if(NoDoubleClickUtils.isDoubleClick()) return;
                CityInfo cityInfo = cityListData.get(position);
                if(cityInfo.isTop()){
                    if(StringUtils.isTrimEmpty(nowCity)){
                        showToast("未获取到当前位置信息");
                    }else{
                        BaiDuLocationInfo baiDuLocationInfo = new BaiDuLocationInfo();
                        baiDuLocationInfo.setCity(nowCity);
                        baiDuLocationInfo.setLat(lat);
                        baiDuLocationInfo.setLng(lat);
                        finishToBack(baiDuLocationInfo);
                    }
                }else{
                    BaiDuLocationInfo baiDuLocationInfo = new BaiDuLocationInfo();
                    baiDuLocationInfo.setCity(cityInfo.getName());
                    finishToBack(baiDuLocationInfo);
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        recycler.setAdapter(cityAdapter);
        suspensionDecoration = new SuspensionDecoration(mContext, cityListData);
        recycler.addItemDecoration(suspensionDecoration);
        //indexbar初始化
        ibRightIndexBar.setmPressedShowTextView(tvSideBarHint)//设置HintTextView
                .setNeedRealIndex(false)//设置需要真实的索引
                .setSourceDatasAlreadySorted(false)
                .setmLayoutManager(layoutManager);//设置RecyclerView的LayoutManager
        loadJsonData();
    }

    private void finishToBack(BaiDuLocationInfo baiDuLocationInfo){
        if(eventTag > -1){
            EventBus.getDefault().post(new ChooseCityEvent(eventTag, baiDuLocationInfo));
        }
        Intent intent = new Intent();
        intent.putExtra("entity", baiDuLocationInfo);
        setResult(RESULT_OK, intent);
        finish();
    }

    private void requestAppPermissions() {
        AndPermission.with(this)
                .permission(Permission.LOCATION, Permission.STORAGE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        if (!AppApplication.getInstances().getLocationService().isStart()) {
                            AppApplication.getInstances().getLocationService().start();
                        }
                        AppApplication.getInstances().getLocationService().registerListener(mListener);
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                            AndPermission.defaultSettingDialog(mContext, Constants.REQUEST_CODE_LOACTION).show();
                        } else {
                            showToast(getStringSource(R.string.app_name) + "需要您授权位置服务和访问文件的权限");
                        }
                    }
                })
                .requestCode(Constants.REQUEST_CODE_CARAME)
                .rationale((requestCode, rationale) -> AndPermission.rationaleDialog(mContext, rationale).show()).start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 0){
                List<CityInfo> list = (List<CityInfo>) msg.obj;
                cityListData.clear();
                cityListData.addAll(list);
                cityAdapter.notifyDataSetChanged();
                ibRightIndexBar.setmSourceDatas(cityListData)//设置数据
                        .invalidate();
                suspensionDecoration.setmDatas(cityListData);
                requestAppPermissions();
            }else if(msg.what == 1){
                if(cityListData != null && cityListData.size() > 0){
                    BDLocation location = (BDLocation) msg.obj;
                    lat = location.getLatitude();
                    lng = location.getLongitude();
                    if(!nowCity.equals(location.getCity())){
                        nowCity = location.getCity();
                        cityListData.get(0).setName("当前位置：" + location.getCity());
                        cityAdapter.notifyDataSetChanged();
                    }
                }
            }
        }
    };

    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                LogUtils.e("home-----------------:" + location.getAddrStr());
                if(!StringUtils.isTrimEmpty(location.getCity())){
                    Message msg = new Message();
                    msg.obj = location;
                    msg.what = 1;
                    handler.sendMessage(msg);
                }
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {
            super.onConnectHotSpotMessage(s, i);
        }

        @Override
        public void onLocDiagnosticMessage(int locType, int diagnosticType, String diagnosticMessage) {
            super.onLocDiagnosticMessage(locType, diagnosticType, diagnosticMessage);
            LogUtils.e("定位失败");
        }
    };

    @Override
    protected void onDestroy() {
        handler.removeCallbacksAndMessages(null);
        handler = null;
        AppApplication.getInstances().getLocationService().unregisterListener(mListener);
        mListener = null;
        super.onDestroy();
    }

    private void loadJsonData() {
        new Thread(() -> {
            try {
                //将json数据变成字符串
                StringBuilder stringBuilder = new StringBuilder();
                try {
                    //获取assets资源管理器
                    AssetManager assetManager = mContext.getAssets();
                    //通过管理器打开文件并读取
                    BufferedReader bf = new BufferedReader(new InputStreamReader(
                            assetManager.open("city.json")));
                    String line;
                    while ((line = bf.readLine()) != null) {
                        stringBuilder.append(line);
                    }
                    Gson gson = new Gson();
                    Type type = new TypeToken<List<CityInfo>>() {
                    }.getType();
                    List<CityInfo> list = gson.fromJson(stringBuilder.toString(), type);
                    CityInfo cityInfoNow = new CityInfo();
                    cityInfoNow.setBaseIndexPinyin("当前位置");
                    cityInfoNow.setTop(true);
                    cityInfoNow.setBaseIndexTag("#");
                    cityInfoNow.setName("正在定位");
                    cityInfoNow.setPinyin("#");
                    list.add(0, cityInfoNow);
                    Message msg = new Message();
                    msg.obj = list;
                    msg.what = 0;
                    handler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

}
